#pragma once

#define FIFO_FILE "file"
#define PATH "."


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstring>
#include <iostream>
#include <unistd.h>

class NamePipe
{
public:
    NamePipe(const std::string& Path, const std::string& Name)
    :_Path(Path),_Name(Name)
    {
        umask(0); 
       _PipeName=_Path+"/"+_Name;
       int ret=mkfifo(_PipeName.c_str(),0666);
       if(ret==0)
       {
            std::cout<<"make mkfifo success"<<std::endl;
       }
       else
       {
            std::cerr<<"make mkfifo unsuccess"<<std::endl;
       }
    }

    ~NamePipe()
    {
        int n=unlink(_PipeName.c_str());
        if(n==0)
        {
            std::cout<<"fifo file delete success"<<std::endl;
        }
        else
        {
            std::cerr<<"fifo file delete unsuccess"<<std::endl;
        }
    }
private:
    std::string _Path;
    std::string _Name;
    std::string _PipeName;
};

class FileOperator
{
public:
    FileOperator(const std::string& Path, const std::string& Name)
    :_Path(Path),_Name(Name),_fd(-1)
    {
        _PipeName=_Path+"/"+_Name;
    }

    void OpenFileForRead()
    {
        _fd=open(_PipeName.c_str(),O_RDONLY);
        if(_fd<0)
        {
            std::cerr<<"open file failed,status is read"<<std::endl;
        }
        else
        {
            std::cout<<"open file success"<<std::endl;
        }
    }

    void OpenFileForWrite()
    {
        _fd=open(_PipeName.c_str(),O_WRONLY);
        if(_fd<0)
        {
            std::cerr<<"open file failed,status is write"<<std::endl;
        }
        else
        {
            std::cout<<"open file success"<<std::endl;
        }
    }

    void Read()
    {
        while(true)
        {
            char buffer[1024];
            // std::string mes;
            // std::getline(std::cin,mes);
            ssize_t ret=read(_fd,buffer,sizeof(buffer)-1);
            if(ret<0)
            {
                std::cerr<<"read failed"<<std::endl;
                break;
            }
            else if(ret==0)
            {
                std::cout<<"write closed"<<std::endl;
                break;
            }
            else
            {
                buffer[ret]=0;
                std::cout<<"Client 发送了："<<buffer<<std::endl;
            }
        }
    }
    void Write()
    {
        std::string message;
        int cnt = 1;
        pid_t id = getpid();
        while (true)
        {
            std::cout << "Please Enter# ";
            std::getline(std::cin, message);
            message += (", message number: " + std::to_string(cnt++) + ", [" + std::to_string(id) + "]");
            write(_fd, message.c_str(), message.size());
        }
    }
    void Close()
    {
        if(_fd>0)close(_fd);
    }

    ~FileOperator(){}
private:
    std::string _Path;
    std::string _Name;
    std::string _PipeName;
    int _fd;
};

